package com.serve.oa.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
public class WebInvokeTimeInterceptor implements HandlerInterceptor {

    private static final ThreadLocal<Long> startTimeThreadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //log.info("preHandle: 接口时间拦截器");
        StringBuffer requestURL = request.getRequestURL();
        log.info("接口地址 URL: {}", requestURL);
        String method = request.getMethod();
        log.info("接口请求方式: {}", method);
        Map<String, String[]> parameterMap = request.getParameterMap();
        // 遍历Map并打印所有请求参数
        parameterMap.forEach((k,i)->{
            String valuesStr = Arrays.stream(i)
                    .collect(Collectors.joining(", ")); // 将数组中的字符串用逗号分隔拼接
            log.info("参数名: {} , 参数值: {}", k, valuesStr);
        });

        String requestURI = request.getRequestURI();
        //log.info("接口请求路径 URI: {}", requestURI);
        long startTime = System.currentTimeMillis();
       // log.info("接口开始时间: {}", startTime);
        startTimeThreadLocal.set(startTime);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        long endTime = System.currentTimeMillis();
        //log.info("接口结束时间: {}", endTime);
        long startTime = startTimeThreadLocal.get();
        log.info("接口耗时: {}ms", endTime - startTime);
        startTimeThreadLocal.remove();
    }
}
